import { createRouter, createWebHistory } from 'vue-router';
import axios from 'axios';
axios.defaults.baseURL = 'http://127.0.0.1:8100/api';
const protectedRoutes = ['main', 'cloud', 'crash', 'user', 'download', 'account', 'devices', 'phone', 'email', 'password', 'records'];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/index',
      name: 'index',
      component: () => import('@/views/index.vue')
    },
    {
      path: '/main',
      name: 'main',
      component: () => import('@/views/main.vue'),
      children: [
        {
          path: '',
          name: 'cloud',
          component: () => import('@/views/cloud.vue'),
        },
        {
          path: '',
          name: 'crash',
          component: () => import('@/views/crash.vue'),
        },
        {
          path: '',
          name: 'user',
          component: () => import('@/views/user.vue'),
        },
        {
          path: '',
          name: 'download',
          component: () => import('@/views/download.vue'),
        }
      ]
    },
    {
      path: '/reg',
      name: 'reg',
      component: () => import('@/views/reg.vue')
    },
    {
      path: '/ucenter',
      name: 'ucenter',
      component: () => import('@/views/ucenter.vue'),
      children: [
        {
          path: '',
          redirect: '/ucenter/account'
        },
        {
          path: 'account',
          name: 'account',
          component: () => import('@/components/account.vue')
        },
        {
          path: 'phone',
          name: 'phone',
          component: () => import('@/components/phone.vue')
        },
        {
          path: 'password',
          name: 'password',
          component: () => import('@/components/password.vue')
        },
        {
          path: 'email',
          name: 'email',
          component: () => import('@/components/email.vue')
        },
        {
          path: 'devices',
          name: 'devices',
          component: () => import('@/components/devices.vue')
        },
        {
          path: 'records',
          name: 'records',
          component: () => import('@/components/records.vue')
        }
      ]
    }
  ]
});

router.beforeEach(async (to, from, next) => {
  if (protectedRoutes.includes(to.name)) {
    const token = localStorage.getItem('authToken');
    if (!token) {
      // 如果 token 不存在，跳转到 index
      next({ name: 'index' });
    } else {
      try {
        // 调用后端 verifyToken 接口
        const response = await axios.post('/verifyToken', { token });
        const { data } = response.data;

        if (data && data.claims) {
          const currentTime = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
          const expirationTime = data.claims.exp; // 过期时间

          if (expirationTime > currentTime) {
            next(); // token 未过期，允许进入
          } else {
            // token 已过期，清除本地 token，并跳转到 index
            localStorage.removeItem('authToken');
            next({ name: 'index' });
          }
        } else {
          // 如果没有 claims 数据，跳转到 index
          next({ name: 'index' });
        }
      } catch (error) {
        console.error('Token verification failed:', error);
        localStorage.removeItem('authToken');
        next({ name: 'index' });
      }
    }
  } else {
    next(); // 不需要保护的路由直接放行
  }
});

export default router;
